package com.example.security.assembly;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class LoginFailHandler implements AuthenticationFailureHandler {

    private static final byte[] MSG_ARR = "登录失败".getBytes(StandardCharsets.UTF_8);

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.error("登录异常", exception);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        ByteArrayInputStream in = new ByteArrayInputStream(MSG_ARR);
        IOUtils.copy(in,response.getOutputStream());
    }
}
